import axios, {AxiosResponse, AxiosRequestConfig} from 'axios';
import {ref} from "vue";
import router from "@/router";

const service = axios.create({
    baseURL: 'http://127.0.0.1:18000/course/',
    timeout: 10000, // 设置请求超时时间
});

// Request interceptors
service.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        const user = localStorage.getItem('user');
        const token = ref('');
        if (user !== null) {
            const userObj = JSON.parse(user);
            try {
                token.value = userObj.userInfo.token;
            } catch (e) {
                console.log("未登陆")
            }
        }
        if (token.value !== undefined && token.value !== ''){
            config.headers.satoken = token.value;
        }
        return config;
    },
    (error: any) => {
        Promise.reject(error).then(r => {
        });
    }
);

// Response interceptors
service.interceptors.response.use(
    async (response: AxiosResponse) => {
        if (response.data.code === 401) {
            await router.push('/login')
        }
        return response.data;
    },
    (error: any) => {
        // do something
        return Promise.reject(error);
    }
);

export default service;
